const express = require('express');
const router = express.Router();
const db = require('../db/db');
const jwt = require('jsonwebtoken');
const config = require('../config');

router.get('/signin', (req, res) => {
    res.render('signin')
})

router.post('/api/signin', async (req, res) => {
    let accoutRes = await db.User.Model.find({ account: req.body.account })
        .exec()
        .then(result => {
            return result;
        })
        .catch(err => {
            console.log(err)
        });
    if (accoutRes.length === 0) {
        res.send({ code: 5002, message: '账号尚未注册，请核实后再登陆！' });
        return;
    }
    let signinRes = await db.User.Model.findOne(req.body)
        .select('name account createTime _id')
        .exec()
        .then(result => {
            return result;
        })
        .catch(err => {
            console.log(err)
        });

    if (!signinRes) {
        res.send({ code: 5003, message: '账号或密码错误' });
    } else {
        req.session.user = signinRes;
        let token = jwt.sign({ name: signinRes.name, id: signinRes.id }, config.secret, { expiresIn: 60 * 60 });
        // console.log(token)
        // console.log(signinRes)
        res.send({ code: 0, message: '登录成功', token: token });
    }
})

router.post('/api/logout', (req, res) => {
    req.session.user = null;
    res.send({ code: 0, message: '退出成功！' })
})

module.exports = router;